from datetime import datetime, timedelta
import time

from flask import render_template, request, jsonify, current_app, session, redirect, url_for, g

from info import constants, db
from info.models import User, News
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import admin_blue


@admin_blue.route('/news_review_detail', methods=['GET', 'POST'])
def news_review_detail():
	"""新闻审核"""
	if request.method == 'GET':
		# 获取新闻id
		news_id = request.args.get("news_id")
		if not news_id:
			return render_template('admin/news_review_detail.html', data={"errmsg": "未查询到此新闻"})

		# 通过id查询新闻
		news = None
		try:
			news = News.query.get(news_id)
		except Exception as e:
			current_app.logger.error(e)

		if not news:
			return render_template('admin/news_review_detail.html', data={"errmsg": "未查询到此新闻"})

		# 返回数据
		data = {"news": news.to_dict()}
		return render_template('admin/news_review_detail.html', data=data)

	# POST请求
	# 1.获取参数
	news_id = request.json.get("news_id")
	action = request.json.get("action")

	# 2.判断参数
	if not all([news_id, action]):
		return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
	if action not in ("accept", "reject"):
		return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

	news = None
	try:
		# 3.查询新闻
		news = News.query.get(news_id)
	except Exception as e:
		current_app.logger.error(e)

	if not news:
		return jsonify(errno=RET.NODATA, errmsg="未查询到数据")

	# 4.根据不同的状态设置不同的值
	if action == "accept":
		news.status = 0
	else:
		# 拒绝通过，需要获取原因
		reason = request.json.get("reason")
		if not reason:
			return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
		news.reason = reason
		news.status = -1

	# 保存数据库
	try:
		db.session.commit()
	except Exception as e:
		current_app.logger.error(e)
		db.session.rollback()
		return jsonify(errno=RET.DBERR, errmsg="数据保存失败")
	return jsonify(errno=RET.OK, errmsg="操作成功")

@admin_blue.route('/news_review')
def news_review():
	"""返回待审核新闻列表"""

	page = request.args.get("p", 1)
	try:
		page = int(page)
	except Exception as e:
		current_app.logger.error(e)
		page = 1

	news_list = []
	current_page = 1
	total_page = 1

	try:
		paginate = News.query.filter(News.status != 0) \
			.order_by(News.create_time.desc()) \
			.paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)

		news_list = paginate.items
		current_page = paginate.page
		total_page = paginate.pages
	except Exception as e:
		current_app.logger.error(e)

	news_dict_list = []
	for news in news_list:
		news_dict_list.append(news.to_review_dict())

	context = {"total_page": total_page, "current_page": current_page, "news": news_dict_list}

	return render_template('admin/news_review.html', data=context)


@admin_blue.route('/user_list')
def user_list():
	"""获取用户列表"""

	# 获取参数
	page = request.args.get("p", 1)
	try:
		page = int(page)
	except Exception as e:
		current_app.logger.error(e)
		page = 1

	# 设置变量默认值
	users = []
	current_page = 1
	total_page = 1

	# 查询数据
	try:
		paginate = User.query.filter(User.is_admin == False).order_by(User.last_login.desc()).paginate(page,
		                                                                                               constants.ADMIN_USER_PAGE_MAX_COUNT,
		                                                                                               False)
		users = paginate.items
		current_page = paginate.page
		total_page = paginate.pages
	except Exception as e:
		current_app.logger.error(e)

	# 将模型列表转成字典列表
	users_list = []
	for user in users:
		users_list.append(user.to_admin_dict())

	context = {"total_page": total_page, "current_page": current_page, "users": users_list}

	return render_template('admin/user_list.html', data=context)


@admin_blue.route('/user_count')
def user_count():
	# 获取用户总人数
	total_count = 0
	try:
		total_count = User.query.filter(User.is_admin == False).count()
	except Exception as e:
		current_app.logger.error(e)
		return jsonify(errno=RET.DBERR, errmsg='数据库查询失败')

	# 获取用户月增人数
	mon_count = 0
	# 2018-6-4 2018-6-1 00:00:00
	# 获取数据库中大于当月零点零时零分的数据
	# 2018-06-01 00:00:00 --> 日期格式

	# 1.获取当前时间
	now_date = time.localtime()

	# 2.将字符串转换成日期
	mon_begin_data = datetime.strptime('%d-%02d-01' % (now_date.tm_year, now_date.tm_mon), '%Y-%m-%d')

	# 3.查询数据库
	try:
		mon_count = User.query.filter(User.is_admin == False, User.create_time >= mon_begin_data).count()
	except Exception as e:
		current_app.logger.error(e)
		return jsonify(errno=RET.DBERR, errmsg='数据库查询失败')

	# 用户日增数
	day_count = 0

	try:
		day_begin = '%d-%02d-%02d' % (now_date.tm_year, now_date.tm_mon, now_date.tm_mday)
		day_begin_date = datetime.strptime(day_begin, '%Y-%m-%d')
		day_count = User.query.filter(User.is_admin == False, User.create_time > day_begin_date).count()
	except Exception as e:
		current_app.logger.error(e)

	# 获取一天的活跃数(最后登录的)
	now_date = datetime.strptime(datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d')

	active_date = []
	active_count = []

	for i in range(0, 31):
		begin_date = now_date - timedelta(days=i)
		end_date = now_date - timedelta(days=(i - 1))

		active_date.append(begin_date.strftime('%Y-%m-%d'))
		count = 0

		# 数据库查询
		try:
			count = User.query.filter(User.is_admin == False, User.last_login >= begin_date,
			                          User.last_login < end_date).count()
		except Exception as e:
			current_app.logger.error(e)
		active_count.append(count)

	active_count.reverse()
	active_date.reverse()

	data = {
		'total_count': total_count,
		'mon_count': mon_count,
		'day_count': day_count,
		'active_date': active_date,
		'active_count': active_count
	}

	return render_template('admin/user_count.html', data=data)


@admin_blue.route('/index')
@user_login_data
def index():
	user = g.user
	data = {
		'user': user.to_dict()
	}
	return render_template('admin/index.html', data=data)


@admin_blue.route('/login', methods=['GET', 'POST'])
def admin_login():
	if request.method == 'GET':
		# 获取session内容
		user_id = session.get('user_id', None)
		is_admin = session.get('is_admin', False)

		# 如果存在登录  直接跳转到后台主页面
		if is_admin and user_id:
			return redirect(url_for('admin.index'))

		return render_template('admin/login.html')

	# POST
	# 获取参数
	username = request.form.get('username')
	password = request.form.get('password')

	# 校验参数
	if not all([username, password]):
		return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

	# 数据库查询
	try:
		user = User.query.filter(User.mobile == username, User.is_admin == True).first()
	except Exception as e:
		current_app.logger.error(e)
		return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

	# 判断用户名和密码
	if not user or not user.check_passowrd(password):
		return render_template('admin/index.html', errmsg='用户名或密码错误')

	# 保存状态到session
	session['user_id'] = user.id
	session['nick_name'] = user.nick_name
	session['mobile'] = user.mobile
	session['is_admin'] = user.is_admin

	return redirect(url_for('admin.index'))
